<template>
	<SkeletonScreen v-if="loading"></SkeletonScreen>
	<view class="container">
		<!-- 用户信息部分 -->
		<view class="user-info">
			<text class="username">小程序用户 {{users.openId}}</text>
			<text class="expire-info">SVIP会员：{{timeStatus}} 到期，购后有效期将延长</text>
		</view>

		<!-- 分割线 -->
		<view class="divider"></view>

		<!-- 会员类型标题 -->
		<view class="section-title">
			<text>VIP会员</text>
			<text class="subtitle">手机/平板/电脑均可使用</text>
		</view>

		<!-- 会员选项 -->
		<view class="membership-options">

			<!-- 连续包年选项 -->
			<view class="option-card" v-for="(item , index ) in coinAlpayValue"
				:class="{ 'active': selectedOption === index }" @click="selectOption(index)">
				<view class="option-header">
					<text class="option-title">查好人生·开播特惠</text>
					<text class="option-type">{{item.name}}</text>
				</view>
				<view class="option-price">
					<text class="current-price">¥{{item?.currentPrice}}</text>
					<text class="original-price">¥{{item?.originalPrice}}</text>
				</view>
				<view class="corner-tag" v-if="selectedOption === index">省¥&nbsp;{{discountAmount}}</view>
			</view>

		</view>

		<!-- 会员权限提示 -->
		<view class="privileges-section">
			<view class="section-header">
				<text class="title">会员特权</text>
				<text class="subtitle">开通即享以下所有权益</text>
			</view>

			<view class="privileges-grid">
				<view class="privilege-item" v-for="item in privileges" :key="item.id">
					<image class="privilege-icon" :src="item.icon" mode="aspectFit"></image>
					<text class="privilege-text">{{ item.text }}</text>
				</view>
			</view>
		</view>

		<!-- 底部支付按钮 -->
		<view class="payment-footer">
			<view class="price-info">
				<text>确认协议并支付</text>
				<text class="price">¥{{ currentPrice.coinAlpayValue }}</text>
			</view>
			<text class="discount-info">已减¥{{ discountAmount }}</text>
			<navigator url="/pages/alpay/content/content" class="agreement-text">开通前请阅读《小程序系列会员服务协议》</navigator>
			<button class="payment-button" @click="handlePayment">立即支付</button>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		coinAlpay
	} from '@/API/alpayApis.js';
	const loading = ref(true)
	const coinAlpayValue = ref([]); //金额

	const users = ref([]);
	const timeStatus = ref();

	// 当前选中的选项
	const selectedOption = ref(0);

	// 会员金额
	const coinAlpayFunction = async () => {
		let res = await coinAlpay();
		coinAlpayValue.value = res.data;
		console.log("金额：", res.data);
		timeStatus.value = formatTimestamp(user.statusCreate);
		loading.value = false
	}
	// 会员金额
	coinAlpayFunction();
	// 时间码转换
	function formatTimestamp(timestamp) {
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
		const day = String(date.getDate()).padStart(2, '0');
		const hour = String(date.getHours()).padStart(2, '0');
		const minute = String(date.getMinutes()).padStart(2, '0');

		return `${year}-${month}-${day} ${hour}:${minute}`;
	}


	// 会员特权数据
	const privileges = ref([{
			id: 1,
			text: '免广告特权',
			icon: '/static/coin_icon/mian.png'
		},
		{
			id: 2,
			text: '高清画质',
			icon: '/static/coin_icon/gao.png'
		},
		{
			id: 3,
			text: '无观看限制',
			icon: '/static/coin_icon/camera.png'
		},
		{
			id: 4,
			text: '会员专属内容',
			icon: '/static/coin_icon/hui.png'
		},
		{
			id: 5,
			text: '多设备使用',
			icon: '/static/coin_icon/duo.png'
		},
		{
			id: 6,
			text: '提前观看',
			icon: '/static/coin_icon/eye.png'
		},
	])

	// 计算当前价格
	const currentPrice = computed(() => {
		const coin = [];
		coin.coinAlpayValue = coinAlpayValue?.value[selectedOption.value]?.currentPrice;
		coin.coinDays = coinAlpayValue?.value[selectedOption.value]?.days;
		return coin;
	})

	// 计算折扣金额
	const discountAmount = computed(() => {
		const option = coinAlpayValue?.value[selectedOption.value];
		return option?.originalPrice - option?.currentPrice;
	})

	// 选择会员选项
	const selectOption = (option) => {
		selectedOption.value = option;
		uni.pageScrollTo({
			scrollTop: 500,
			duration: 800
		})
	}

	// 获取用户授权
	async function getAuth() {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title: '授权提示',
				content: '需要获取您的授权以完成支付',
				success: async (res) => {
					if (res.confirm) {
						try {
							// 1. 获取微信登录code
							const loginRes = await uni.login({
								provider: 'weixin'
							});
							
							if (!loginRes.code) {
								throw new Error('获取登录code失败');
							}
							
							// 2. 将code发送到后端获取openid
							const apiRes = await uni.request({
								url: 'https://min.erkantv.cn:443/api/auth/getOpenId',
								method: 'POST',
								header: {
									'Content-Type': 'application/json'
								},
								data: {
									code: loginRes.code
								}
							});
							
							if (apiRes.data.code === 200) {
								// 3. 保存用户信息
								const user = {
									openId: apiRes.data.data.openId,
									id: apiRes.data.data.userId
								};
								uni.setStorageSync("user", user);
								resolve();
							} else {
								reject(new Error(apiRes.data.message || '获取openId失败'));
							}
						} catch (err) {
							console.error('授权流程错误:', err);
							reject(err);
						}
					} else {
						reject(new Error('用户拒绝授权'));
					}
				}
			});
		});
	}

	// 处理支付
	const handlePayment = async () => {
		try {
			// 1. 检查用户授权状态
			let user = uni.getStorageSync("user");
			if (!user || !user.openId) {
				// 2. 未授权时获取用户授权
				await getAuth();
				user = uni.getStorageSync("user");
				if (!user || !user.openId) {
					uni.showToast({
						title: '需要授权才能继续支付',
						icon: 'none'
					});
					return;
				}
			}
			
			// 3. 执行支付流程
			uni.showToast({
				title: `支付¥${currentPrice.value.coinAlpayValue}`,
				icon: 'none'
			});
			
			const days = currentPrice.value.coinDays;
			const amount = currentPrice.value.coinAlpayValue;
			console.log("天数{},价格{}：", days, amount);
			
			requestPayment(amount, days, user.openId, user.id);
		} catch (error) {
			console.error('支付流程错误:', error);
			uni.showToast({
				title: '支付流程出错: ' + error.message,
				icon: 'none'
			});
		}
	}


	// H5公众号支付(JSP支付方式)
	function requestPayment(totalFee, days, openId, UserId) {
		// 1. 调用后端创建支付订单
		uni.request({
			url: 'https://min.erkantv.cn:443/api/pay/createOrder',
			method: 'POST',
			data: {
				amount: totalFee, // 金额(元)
				productId: 'VIP_' + days + 'DAYS', // 商品ID
				openId: openId, // 用户openId
				userId: UserId // 用户ID
			},
			success(res) {
				if (res.data.code === 200) {
					// 2. 获取支付参数后跳转支付页面
					const payUrl = res.data.data.payUrl;
					
					// 3. 跳转到支付页面(公众号支付)
					window.location.href = payUrl;
					
					// 4. 支付成功后回调处理(后端会通知前端支付结果)
					// 这里可以添加轮询逻辑检查支付状态
					checkPaymentStatus(res.data.data.orderNo, UserId, days);
				} else {
					uni.showToast({
						title: '创建订单失败: ' + res.data.message,
						icon: 'none'
					});
				}
			},
			fail(err) {
				uni.showToast({
					title: '网络错误: ' + err.errMsg,
					icon: 'none'
				});
			}
		});
	}
	
	// 检查支付状态
	function checkPaymentStatus(orderNo, UserId, days) {
		let retryCount = 0;
		const maxRetry = 10;
		const interval = 3000; // 3秒轮询一次
		
		const timer = setInterval(() => {
			if (retryCount >= maxRetry) {
				clearInterval(timer);
				uni.showToast({
					title: '支付状态查询超时',
					icon: 'none'
				});
				return;
			}
			
			uni.request({
				url: 'https://min.erkantv.cn:443/api/pay/checkStatus',
				method: 'GET',
				data: {
					orderNo: orderNo
				},
				success(res) {
					if (res.data.code === 200 && res.data.data.paid) {
						clearInterval(timer);
						// 支付成功处理
						handlePaymentSuccess(UserId, days);
					}
					retryCount++;
				}
			});
		}, interval);
	}
	
	// 支付成功处理
	function handlePaymentSuccess(UserId, days) {
		let now = new Date();
		let oneDayLater = new Date(now);
		oneDayLater.setDate(now.getDate() + days);
		
		// 更新会员状态
		uni.request({
			url: 'https://min.erkantv.cn:443/portal/openId/updateStatus',
			method: 'GET',
			data: {
				id: UserId,
				status: 1,
				statusCreate: oneDayLater.getTime()
			},
			success: (e) => {
				uni.showLoading({
					title: '数据更新中...',
				});
				setTimeout(() => {
					uni.hideLoading();
					uni.showToast({
						title: '支付成功！会员已开通',
						icon: 'none'
					});
				}, 3000);
			}
		});
	}
	
</script>

<style lang="scss">
	.container {
		padding: 20rpx 30rpx;
		background-color: #000;
		min-height: 100vh;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}

	.user-info {
		display: flex;
		flex-direction: column;
		padding: 20rpx 0;

		.username {
			font-size: 32rpx;
			color: #fff;
			font-weight: bold;
			padding-right: 20rpx;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}

		.expire-info {
			font-size: 26rpx;
			color: #888;
			margin-top: 10rpx;
		}
	}

	.divider {
		height: 1rpx;
		background-color: #333;
		margin: 20rpx 0;
	}

	.section-title {
		display: flex;
		flex-direction: column;
		margin-bottom: 30rpx;

		text {
			font-size: 34rpx;
			color: #fff;
			font-weight: bold;
		}

		.subtitle {
			font-size: 26rpx;
			color: #888;
			font-weight: normal;
			margin-top: 10rpx;
		}
	}

	.membership-options {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		flex: 1;
	}

	.option-card {
		background-color: #1d1d1d;
		border-radius: 16rpx;
		padding: 30rpx;
		position: relative;
		overflow: hidden;
		transition: all 0.3s ease;
		border: 2rpx solid #333;

		&.active {
			border-color: #ff0000;
			background-color: #1d1d1d;
			transform: translateY(-5rpx);
			box-shadow: 0 10rpx 20rpx rgba(255, 0, 0, 0.2);

			.option-type {
				color: #ff0000 !important;
			}
		}

		.option-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.option-title {
				font-size: 30rpx;
				color: #fff;
			}

			.option-type {
				font-size: 28rpx;
				color: #ff3333;
				font-weight: bold;
			}
		}

		.option-price {
			display: flex;
			align-items: flex-end;

			.current-price {
				font-size: 42rpx;
				color: #ff0000;
				font-weight: bold;
			}

			.original-price {
				font-size: 28rpx;
				color: #666;
				text-decoration: line-through;
				margin-left: 15rpx;
				margin-bottom: 4rpx;
			}
		}

		.corner-tag {
			position: absolute;
			right: 0;
			top: 0;
			background-color: #ff0000;
			color: #fff;
			font-size: 22rpx;
			padding: 6rpx 20rpx;
			border-bottom-left-radius: 16rpx;
			transform: translateY(-5rpx);
			animation: bounceIn 0.5s;
		}
	}

	/* 新增的会员特权区域样式 */
	.privileges-section {
		background-color: #1d1d1d;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-top: 40rpx;

		.section-header {
			display: flex;
			flex-direction: column;
			margin-bottom: 30rpx;

			.title {
				font-size: 32rpx;
				color: #fff;
				font-weight: bold;
			}

			.subtitle {
				font-size: 26rpx;
				color: #888;
				margin-top: 10rpx;
			}
		}

		.privileges-grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 30rpx;

			.privilege-item {
				display: flex;
				align-items: center;

				.privilege-icon {
					width: 40rpx;
					height: 40rpx;
					margin-right: 15rpx;
				}

				.privilege-text {
					font-size: 28rpx;
					color: #fff;
				}
			}
		}
	}

	.payment-footer {
		background-color: #1d1d1d;
		padding: 30rpx;
		border-radius: 16rpx;
		margin-top: 40rpx;
		box-shadow: 0 -5rpx 20rpx rgba(0, 0, 0, 0.3);


		.price-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15rpx;

			text {
				font-size: 32rpx;
				color: #fff;
			}

			.price {
				font-size: 40rpx;
				color: #ff0000;
				font-weight: bold;
			}
		}

		.discount-info {
			display: block;
			font-size: 26rpx;
			color: #ff0000;
			text-align: right;
			margin-bottom: 30rpx;
		}

		.agreement-text {
			display: block;
			font-size: 24rpx;
			color: #ff0000;
			text-align: center;
			margin-bottom: 30rpx;
		}

		.payment-button {
			background-color: #ff0000;
			color: #fff;
			border-radius: 50rpx;
			height: 90rpx;
			line-height: 90rpx;
			font-size: 34rpx;
			font-weight: bold;
			transition: all 0.3s;

			&:active {
				opacity: 0.9;
				transform: scale(0.98);
				background-color: #cc0000;
			}
		}
	}

	@keyframes bounceIn {
		0% {
			opacity: 0;
			transform: scale(0.3) translateY(-5rpx);
		}

		50% {
			opacity: 1;
			transform: scale(1.05) translateY(-5rpx);
		}

		100% {
			transform: scale(1) translateY(-5rpx);
		}
	}
</style>